(function () {

	'use strict';

	angular
		.module('app')
		.controller('AddressSelectController', AddressSelectController);

	AddressSelectController.$inject = ['$scope', '$http', '$stateParams', '$rootScope', '$state', 'API', 'ENUM', 'AddressEditModel', 'AddressSelectModel'];

	function AddressSelectController($scope, $http, $stateParams, $rootScope, $state, API, ENUM, AddressEditModel, AddressSelectModel) {

		$scope.selectedId = $stateParams.address_id;

		$scope.addressSelectModel = AddressSelectModel;
        $scope.addressEditModel = AddressEditModel;

		$scope.touchCreate = function () {
            $scope.addressEditModel.clear();
            $scope.addressEditModel.address = null;

            $state.go('address-edit', {});
        };

		$scope.touchModify = function (address) {
            $scope.addressEditModel.clear();
            $scope.addressEditModel.address = address;

            $state.go('address-edit', {});
        };

		$scope.touchConsignee = function (address) {
            $rootScope.$emit('consigneeChanged', address);
            $scope.goBack();
        };

		$scope.touchDefaultAddress = function (addressID)  {
            API.consignee.setDefault({address_id: addressID}).then(function(res) {
                if ( res ) {
                    for (var i = 0; i < $scope.addressSelectModel.addList.length; i++) {
                        var address = $scope.addressSelectModel.addList[i];
                        if ( address.address_id == addressID ) {
                            address.is_default = true;
                        } else {
                            address.is_default = false;
                        }
                    }
                } else {
                    $scope.toast('设置失败');
                }
            });
        };

		$scope.isDefaultAddress = function (address) {
            if ( address.is_default ) {
                return true;
            }else {
                return false;
            }
        };


		$scope.addressSelectModel.clear();
		$scope.addressSelectModel.reload();
	}

})();
